package com.wlts.wzy.SelfModule.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.kuaishou.merchant.open.api.KsMerchantApiException;
import com.kuaishou.merchant.open.api.client.AccessTokenKsMerchantClient;
import com.kuaishou.merchant.open.api.request.KsMerchantItemAddRequest;
import com.kuaishou.merchant.open.api.request.KsMerchantItemDeleteRequest;
import com.kuaishou.merchant.open.api.request.KsMerchantItemDetailImagesUpdateRequest;
import com.kuaishou.merchant.open.api.request.KsMerchantItemStatusUpdateRequest;
import com.kuaishou.merchant.open.api.request.param.item.MerchantServiceRuleParam;
import com.kuaishou.merchant.open.api.request.param.item.MerchantSkuInfoParam;
import com.kuaishou.merchant.open.api.response.KsMerchantItemAddResponse;
import com.kuaishou.merchant.open.api.response.KsMerchantItemDeleteResponse;
import com.kuaishou.merchant.open.api.response.KsMerchantItemDetailImagesUpdateResponse;
import com.kuaishou.merchant.open.api.response.KsMerchantItemStatusUpdateResponse;
import com.wlts.wzy.Base.BaseEntity;
import com.wlts.wzy.KSUserModule.entity.KsOauth;
import com.wlts.wzy.KSUserModule.entity.KsStoreUser;
import com.wlts.wzy.KSUserModule.util.KsConfig;
import com.wlts.wzy.LMGoodsModule.entity.LmGoods;
import com.wlts.wzy.Result.Result;
import com.wlts.wzy.SelfModule.entity.SelfMyGoods;
import com.wlts.wzy.SelfModule.service.ISelfGoodsService;
import com.wlts.wzy.SelfModule.service.ISelfMyGoodsService;
import com.wlts.wzy.api.request.ks.StatusUpdateGoodsToKSRequest;
import com.wlts.wzy.api.request.lm.LmDelGoodsToKSRequest;
import com.wlts.wzy.api.request.lm.LmPutGoodsToKSRequest;
import com.wlts.wzy.api.vo.LmGoodsSkuVO;
import com.wlts.wzy.api.vo.SelfVO.SelfGoodsSkuVO;
import com.wlts.wzy.configBean.KsConfig.KsConfigInfo;
import com.wlts.wzy.expand.MyLambdaQueryWrapper;
import com.wlts.wzy.util.CopyUtils;
import com.wlts.wzy.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 我的自营商品表 前端控制器
 * </p>
 *
 * @author zhiyong
 * @since 2021-03-19
 */
@Api(tags = "我的自营商品表 推送快手控制器",position = 20)
@ApiSort(value = 10)
@RestController
@RequestMapping("/SelfModule/self-my-goods/ks")
public class KSSelfMyGoodsController {
    @Autowired
    private ISelfMyGoodsService selfMyGoodsService;

    @Autowired
    private KsConfig ksConfig;

    @ApiOperation(value = "推送自营商品到KS小店")
    @RequestMapping(value = "lmPutGoodsToKS", method = RequestMethod.POST)
    public Result<KsMerchantItemAddResponse> LmPutGoodsToKS(@RequestBody LmPutGoodsToKSRequest request) throws KsMerchantApiException {

        KsStoreUser ksStoreUser = ksConfig.getKsStoreUserConfig();

        KsOauth ksOauth = ksStoreUser.getKsOauth();

        if (ksOauth == null) {
            return Result.buildResult(500, "账号未授权");
        }


        MyLambdaQueryWrapper<SelfMyGoods> wrapper = new MyLambdaQueryWrapper<>();
        wrapper.eq(SelfMyGoods::getUserUuid, ksStoreUser.getUuid());
        wrapper.eq(SelfMyGoods::getId, request.getId());
        wrapper.eq(BaseEntity::getDelFlag, "0");

        SelfMyGoods lmSelfGoods = selfMyGoodsService.getOne(wrapper);

        if (lmSelfGoods == null) {
            return Result.buildResult(500, "商品不存在");
        }

        if (lmSelfGoods.getKsSellStatus() == 1) {
            return Result.buildResult(500, "商品已上架");
        }

        List<SelfGoodsSkuVO> lmGoodsSkuVOList = JSONArray.parseArray(request.getSkuList(), SelfGoodsSkuVO.class);

        KsMerchantItemAddRequest goods = new KsMerchantItemAddRequest();

        long reItemId = System.currentTimeMillis();

        goods.setAccessToken(ksOauth.getAccessToken());
        goods.setRelItemId(reItemId);
        lmSelfGoods.setRelItemId(reItemId+"");

        String title = lmSelfGoods.getItemTitle();


        if (title.length() > 30) {
            title = title.substring(0, 30);
        }

        List<String> array =JSONArray.parseArray(lmSelfGoods.getMainPicPrl(),String.class);
        goods.setImageUrls(array);
        goods.setTitle(title);
        goods.setDetails(lmSelfGoods.getItemTitle());
        MerchantServiceRuleParam ruleParam = new MerchantServiceRuleParam();
        ruleParam.setRefundRule(request.getRefundRule() + "");
        //   ruleParam.setTheDayOfDeliverGoodsTime(9);
        ruleParam.setPromiseDeliveryTime(request.getPromiseDeliveryTime());

        ruleParam.setDepositRule("1");

        goods.setServiceRule(ruleParam);

        goods.setCategoryId(request.getCategoryId());
        goods.setCategoryName(request.getCategoryName());
        goods.setParentCategoryId(request.getParentCategoryId());
        goods.setParentCategoryName(request.getParentCategoryName());

        List<MerchantSkuInfoParam> skuList = lmGoodsSkuVOList.stream().map(lmGoodsSkuVO -> {

            MerchantSkuInfoParam param = new MerchantSkuInfoParam();
            param.setRelSkuId(lmGoodsSkuVO.getSkuId());
            param.setSkuNick(lmGoodsSkuVO.getSkuId() + "");
            param.setImageUrl(lmGoodsSkuVO.getSkuPicUrl());
            param.setSkuSpecification(lmGoodsSkuVO.getSkuTitle());
            param.setSkuStock(lmGoodsSkuVO.getStock());
            param.setSkuSalePrice(lmGoodsSkuVO.getPriceCent());
            return param;
        }).collect(Collectors.toList());

        goods.setSkuInfoParams(skuList);

        goods.setExpressTemplateId(request.getExpressTemplateId());


        //       System.out.println(JSON.toJSONString(skuList));


        AccessTokenKsMerchantClient tokenKsMerchantClient
                = new AccessTokenKsMerchantClient("", KsConfigInfo.appKey, KsConfigInfo.signSecret);

        KsMerchantItemAddResponse response = tokenKsMerchantClient.execute(goods);


        if (response.getResult() == 1) {

            lmSelfGoods.setKsGoods(JSON.toJSONString(response.getKsMerchantItemAddData()));

            lmSelfGoods.setKwaiItemId(response.getKsMerchantItemAddData().getKwaiItemId()+"");

            lmSelfGoods.setKsSellStatus(1);


            /**
             * 上传商品详细图
             */
            try {
                List<String> detailImages = JSONArray.parseArray(lmSelfGoods.getPicList(),String.class);
                if (detailImages.size() > 0) {
                    KsMerchantItemDetailImagesUpdateRequest updateRequest = new KsMerchantItemDetailImagesUpdateRequest();
                    updateRequest.setAccessToken(ksOauth.getAccessToken());
                    updateRequest.setDetailImageUrls(detailImages);
                    updateRequest.setKwaiItemId(Long.valueOf(lmSelfGoods.getKwaiItemId()));
                    KsMerchantItemDetailImagesUpdateResponse updateResponse = tokenKsMerchantClient.execute(updateRequest);
                    lmSelfGoods.setDetailsImagesMsg(JSON.toJSONString(updateResponse));
                }
                selfMyGoodsService.updateById(lmSelfGoods);
            } catch (Exception e) {
                e.printStackTrace();
            }

            return Result.buildResult(response);
        } else {
            return Result.buildResult(500, response.getErrorMsg());
        }

    }


    @ApiOperation(value = "删除商品快手平台对应商品")
    @RequestMapping(value = "delLmPutGoodsToKS", method = RequestMethod.POST)
    public Result<KsMerchantItemDeleteResponse> delLmPutGoodsToKS(@RequestBody LmDelGoodsToKSRequest request) throws KsMerchantApiException {

        KsStoreUser ksStoreUser = ksConfig.getKsStoreUserConfig();

        KsOauth ksOauth = ksStoreUser.getKsOauth();

        if (ksOauth == null) {
            return Result.buildResult(500, "账号未授权");
        }

        SelfMyGoods selfGoodsRequest = new SelfMyGoods();

        CopyUtils.copyProperties(request, selfGoodsRequest);

        MyLambdaQueryWrapper<SelfMyGoods> wrapper = new MyLambdaQueryWrapper<>(selfGoodsRequest);

        wrapper.eq(BaseEntity::getDelFlag, "0");

        wrapper.isNotNull(SelfMyGoods::getKwaiItemId);

        wrapper.eq(SelfMyGoods::getKwaiItemId,request.getKwaiItemId());

        SelfMyGoods lmSelfGoods = selfMyGoodsService.getOne(wrapper);

        if (lmSelfGoods == null) {
            return Result.buildResult(500, "商品不存在");
        }

        KsMerchantItemDeleteRequest goods = new KsMerchantItemDeleteRequest();

        goods.setAccessToken(ksOauth.getAccessToken());
        goods.setRelItemId(Long.valueOf(lmSelfGoods.getRelItemId()));
        goods.setKwaiItemId(Long.valueOf(lmSelfGoods.getKwaiItemId()));


        AccessTokenKsMerchantClient tokenKsMerchantClient
                = new AccessTokenKsMerchantClient("", KsConfigInfo.appKey, KsConfigInfo.signSecret);

        KsMerchantItemDeleteResponse response = tokenKsMerchantClient.execute(goods);

        System.out.println(JSON.toJSONString(response));

        if (response.getResult() == 1) {

            lmSelfGoods.setKsSellStatus(2);

            selfMyGoodsService.updateById(lmSelfGoods);

            return Result.buildResult(response);
        } else {
            return Result.buildResult(500, response.getErrorMsg());
        }

    }


    @ApiOperation(value = "上下架快手平台对应商品")
    @RequestMapping(value = "statusUpdateGoodsToKS", method = RequestMethod.POST)
    public Result<KsMerchantItemStatusUpdateResponse> statusUpdateGoodsToKS(@RequestBody StatusUpdateGoodsToKSRequest request) throws KsMerchantApiException {

        KsStoreUser ksStoreUser = ksConfig.getKsStoreUserConfig();

        KsOauth ksOauth = ksStoreUser.getKsOauth();

        if (ksOauth == null) {
            return Result.buildResult(500, "账号未授权");
        }

        SelfMyGoods selfGoodsRequest = new SelfMyGoods();

        CopyUtils.copyProperties(request, selfGoodsRequest);

        MyLambdaQueryWrapper<SelfMyGoods> wrapper = new MyLambdaQueryWrapper<>(selfGoodsRequest);

        wrapper.eq(BaseEntity::getDelFlag, "0");

        wrapper.isNotNull(SelfMyGoods::getKwaiItemId);

        SelfMyGoods lmSelfGoods = selfMyGoodsService.getOne(wrapper);

        if (lmSelfGoods == null) {
            return Result.buildResult(500, "商品不存在");
        }

        if (lmSelfGoods.getKsSellStatus().equals(request.getShelfStatus())) {
            return Result.buildResult();
        }

        KsMerchantItemStatusUpdateRequest goods = new KsMerchantItemStatusUpdateRequest();

        goods.setAccessToken(ksOauth.getAccessToken());
        goods.setRelItemId(Long.valueOf(lmSelfGoods.getRelItemId()));
        goods.setKwaiItemId(Long.valueOf(lmSelfGoods.getKwaiItemId()));
        if(request.getShelfStatus()==2){
            goods.setShelfStatus(0);
        }else {
            goods.setShelfStatus(request.getShelfStatus());
        }

        AccessTokenKsMerchantClient tokenKsMerchantClient
                = new AccessTokenKsMerchantClient("", KsConfigInfo.appKey, KsConfigInfo.signSecret);

        KsMerchantItemStatusUpdateResponse response = tokenKsMerchantClient.execute(goods);


        if (response.getResult() == 1) {

            lmSelfGoods.setKsSellStatus(request.getShelfStatus());

            selfMyGoodsService.updateById(lmSelfGoods);

            return Result.buildResult(response);
        } else {
            return Result.buildResult(500, response.getErrorMsg());
        }

    }

}
